use crate::core::settings::load_settings;
use tauri::{LogicalSize, LogicalPosition, Manager};

/// 显示窗口并重新居中
/// 功能：显示主窗口，重新计算窗口大小和位置，设置窗口置顶并聚焦
/// 参数：app - Tauri应用句柄
/// 返回值：Result<(), String> - 成功返回Ok(())，失败返回错误信息
#[tauri::command]
pub fn show_window(app: tauri::AppHandle) -> Result<(), String> {
    if let Some(window) = app.get_webview_window("main") {
        // 重新计算窗口大小和居中位置
        let (width, height) = calculate_window_size();
        let (x, y) = calculate_center_position(width, height);
        
        // 设置窗口大小和位置
        let _ = window.set_size(LogicalSize::new(width, height));
        let _ = window.set_position(LogicalPosition::new(x, y));
        
        // 设置窗口强制置顶
        window.set_always_on_top(true).map_err(|e| {
            log::warn!("设置窗口置顶失败: {}", e);
            e.to_string()
        })?;
        
        // 显示并聚焦窗口
        window.show().map_err(|e| e.to_string())?;
        window.set_focus().map_err(|e| e.to_string())?;
        
        log::info!("窗口已显示并设置为置顶状态");
    }
    Ok(())
}

/// 隐藏窗口到托盘
/// 功能：隐藏主窗口到系统托盘
/// 参数：app - Tauri应用句柄
/// 返回值：Result<(), String> - 成功返回Ok(())，失败返回错误信息
#[tauri::command]
pub fn hide_window(app: tauri::AppHandle) -> Result<(), String> {
    if let Some(window) = app.get_webview_window("main") {
        window.hide().map_err(|e| e.to_string())?
    }
    Ok(())
}

/// 设置窗口置顶状态
/// 功能：控制窗口是否始终置顶显示
/// 参数：app - Tauri应用句柄，always_on_top - 是否置顶
/// 返回值：Result<(), String> - 成功返回Ok(())，失败返回错误信息
#[tauri::command]
pub fn set_window_always_on_top(app: tauri::AppHandle, always_on_top: bool) -> Result<(), String> {
    if let Some(window) = app.get_webview_window("main") {
        window.set_always_on_top(always_on_top).map_err(|e| {
            log::warn!("设置窗口置顶状态失败: {}", e);
            e.to_string()
        })?;
        
        log::info!("窗口置顶状态已设置为: {}", always_on_top);
    }
    Ok(())
}

/// 获取屏幕分辨率
#[cfg(target_os = "windows")]
fn get_screen_resolution() -> (i32, i32) {
    use winapi::um::winuser::{GetSystemMetrics, SM_CXSCREEN, SM_CYSCREEN};
    unsafe {
        let width = GetSystemMetrics(SM_CXSCREEN);
        let height = GetSystemMetrics(SM_CYSCREEN);
        (width, height)
    }
}

/// 根据设置获取窗口大小，如果设置加载失败则使用屏幕分辨率计算
pub fn calculate_window_size() -> (u32, u32) {
    // 尝试从设置中加载窗口尺寸
    if let Ok(settings) = load_settings() {
        return (settings.window_width as u32, settings.window_height as u32);
    }
    
    // 如果设置加载失败，使用默认计算方式
    #[cfg(target_os = "windows")]
    {
        let (screen_width, screen_height) = get_screen_resolution();
        let width = (screen_width as f64 * 0.5) as u32;
        let height = (screen_height as f64 * 0.55) as u32;
        (width.max(800), height.max(600))
    }
    
    #[cfg(not(target_os = "windows"))]
    {
        (800, 600)
    }
}

/// 计算窗口居中位置
/// 窗口会稍微向上偏移，避免完全居中
pub fn calculate_center_position(window_width: u32, window_height: u32) -> (i32, i32) {
    #[cfg(target_os = "windows")]
    {
        let (screen_width, screen_height) = get_screen_resolution();
        let x = (screen_width - window_width as i32) / 2;
        let y = (screen_height - window_height as i32) / 2 - 50; // 向上偏移50像素
        (x.max(0), y.max(0))
    }
    
    #[cfg(not(target_os = "windows"))]
    {
        (100, 50) // 非Windows系统也稍微向上偏移
    }
}